<template>
  <div style="height: calc(100vh - 30px); padding: 15px; background-color: white">
    <tiny-split v-model="split1" style="z-index: 9">
      <template #left>
        <div style="padding-right: 5px;">
<!--                    <JButton @click="doScan">扫描</JButton>-->
          <div style="padding-left:5px;margin-top: 20px">
            <JButton icon="search" @click="searchByhand" ref="handRef">手工找单</JButton>
          </div>
          <div style="margin-top: 10px;padding:5px;">
            <div>
              <div class="item">
                <span style="width: 120px">应收合计：</span>
                <span class="money">{{ allData.ys }}</span>
              </div>
              <div class="item">
                <span style="width: 120px">涉及商户数：</span>
                <span class="money">{{ allData.shs }}</span>
              </div>
              <div class="item">
                <span style="width: 120px">涉及票据数：</span>
                <span class="money">{{ allData.pjs }}</span>
              </div>
            </div>
          </div>
          <div style="margin-top: 30px;padding:5px;">
            <JAuto v-model="doName" placeholder="经办人" cat="admin" @change="changeDo" />
          </div>
          <div style="margin-top: 20px; text-align: center">
            <JButton type="info" size="medium" @click="confirm">确认派单</JButton>
          </div>
        </div>
      </template>
      <template #right>
        <div class="demo-split-pane">
          <j-grid v-model="hjList" :columns="fields" :offset-bottom="5" />
        </div>
      </template>
    </tiny-split>
  </div>
</template>
<script setup>
import {ref,onActivated,onDeactivated} from "vue";
import tool from "@/utils/tool";
import bus from "@/store/bus";
import JAuto from "@/lui/JAuto.vue";
const split1 = ref('200px')
const salesList = ref([])
const allData = ref({
  ys: '', // 应收
  shs: '', // 商户数
  pjs: '', // 票据数
})
const fields = ref([
  {type: 'index', width: 40,},
  {field: 'buName', title: '终端名称', width: 200,align:'left',filter: true,visible: true},
  {field: 'billDate', title: '日期', width: 100,visible: true,},
  {field: 'billNo', title: '票号', width: 130,canClick: true,visible: true,},
  {field: 'transTypeName', title: '业务类型', width: 100,visible: true,},
  {field: 'salesName', title: '业务员', width: 100,visible: true,},
  {field: 'arrearsReal', title: '应收金额', width: 100,align: 'right',subSum: true,visible: true},
  {field: 'leftAmount', title: '应收结余', width: 100,align: 'right',subSum: true,visible: true,},
  {field: 'remark', title: '备注', width: 100,align: 'right',visible: true,},
  {field: '', title: '操作', width: 60,align: 'right',btns:[{id: 'del',label: '删除',show:"row.transTypeName!=='小计'", click: (row) => {
        del(row)
      }}]},
])
const tuiFields = ref([
  {type: 'index', width: 40,},
  {field: 'buName', title: '终端名称', width: 200,align:'left'},
  {field: 'billDate', title: '日期', width: 100,},
  {field: 'billNo', title: '票号', width: 130,canClick: true,},
  {field: 'transTypeName', title: '业务类型', width: 100,},
  {field: 'salesName', title: '业务员', width: 100,},
  {field: 'arrearsReal', title: '应收金额', width: 100,align: 'right',sum: true},
  {field: 'leftAmount', title: '应收结余', width: 100,align: 'right',sum: true,},
  {field: 'remark', title: '备注', width: 100,align: 'right',},
  {type: 'selection', width: 50},
])
const doId = ref()
const doName = ref()
const hjList = ref([])
const bills = ref([])
const tuiList = ref([])

const doScan = () => {
  tool.post('scan/getIdByNo',{billNo: 'XS-20241128-2'}).then(ret => {
    if(ret.stat) {
      scanPs({code: ret.data})
    }
  })
}
const choseDikou = (sel) => {
  if(sel.length === 0) return tool.err('没有选中抵扣票据')
  for (let i = 0; i < sel.length; i++) {
    let row = sel[i]
    delete row._RID
    salesList.value.push(row)
  }
  sumBills()
}
const cellClick = ({row}) => {
  let code = row.transType + '-' + row.id
  if(row.billState === '草稿') return tool.err('请先审核草稿')
  if(row.billState === '已删除') return tool.err('票据已删除')
  if(row.billState === '已审核')
    scanPs({code})
}
const scanPs = ({code}) => {
  let arr = code.split('-')
  let billId = arr[1]
  let ids = []
  for (let i = 0; i < salesList.value.length; i++) {
    ids.push(tool.xe.toNumber(salesList.value[i].id))
  }
  if(ids.indexOf(tool.xe.toNumber(billId)) !== -1) {
    return tool.warning('该票据已扫描')
  }
  if (Number(arr[0]) === 150601 || Number(arr[0]) === 150602 || Number(arr[0]) === 150603) {
    tool.post('receipt/pdskscan', {billId: tool.xe.toNumber(arr[1])}, true).then(ret => {
      if (ret.stat && ret.data) {
        salesList.value.push(ret.data.list)
        tuiList.value = ret.data.tuiList
        if(tuiList.value.length > 0) {
          let options = {
            title: '可抵扣票据',
            width: 1200,
            height: 500,
            mounted: (api) => {},
            rules: [
              {
                field: 'grid', com: 'JGrid', width: 1100, height: 400,columns: tuiFields.value,
                passList: tuiList.value
              }
            ],
            btns: [
              {
                name: '选中并关闭',inject: true,
                click: (inject, close) => {
                  let sel = inject.exec('grid', 'getSelect')
                  choseDikou(sel)
                  close()
                }
              }
            ]
          }
          tool.editor(options)
        }
        sumBills()
      }
    })
  }
  else {
    return tool.err('非销售票据')
  }
}
const searchByhand = () => {
  let options = {
    title: '选择票据',
    width: 1200,
    height: 700,
    mounted: (api) => {
      options.doSearch(api)
    },
    rules: [
      {
        field: 'tabIndex', type: 'JTab', width: 500,defaultValue: '1天前', list: [
          {id: '1天前', name: '1天前'},
          {id: '1周前', name: '1周前'},
          {id: '1月前', name: '1月前'},
          {id: '3月前', name: '3月前'},
          {id: '6月前', name: '6月前'},
          {id: '1年前', name: '1年前'},
        ],
        inject: true,
        events: {
          change: (inject, val) => {
            if(val === '1天前') {inject.setValue('endDate', tool.getDay('', -1))}
            if(val === '1周前') {inject.setValue('endDate', tool.getDay('', -7))}
            if(val === '1月前') {inject.setValue('endDate', tool.getDay('', -30))}
            if(val === '3月前') {inject.setValue('endDate', tool.getDay('', -90))}
            if(val === '6月前') {inject.setValue('endDate', tool.getDay('', -180))}
            if(val === '1年前') {inject.setValue('endDate', tool.getDay('', -365))}
            options.doSearch(inject)
          }
        }
      },
      {field: 'endDate', width: 180, com: 'JPicker', defaultValue: tool.getDay('', -1)},
      {field: 'exceptPdBill', com: 'JCheck', width: 320, defaultValue: true, label: '过滤已派单并在收款中的票据'},
      {field: 'salesName', idField: 'salesId', width: 150,com: 'JAuto', cat: 'adminList', placeholder: '业务员'},
      {field: 'buName', idField: 'buId', width: 150,com: 'JAuto', cat: 'customer', placeholder: '终端'},
      {field: 'contactCatName',idField: 'contactCatId', width: 150,com: 'JAuto', cat: 'contactCat', placeholder: '终端分类'},
      {field: 'invName',idField: 'invId', width: 150,com: 'JAuto', cat: 'goods', placeholder: '商品'},
      {field: 'billNo', width: 150,com: 'JInput',  placeholder: '单据号'},
      {
        field: '', width: 150,com: 'JButton',  text: '查询',inject: true,types:'success',
        events: {
          click: (inject) => {
            options.doSearch(inject)
          }
        }
      },
      {
        field: 'grid', com: 'JGrid', width: 1150,height: 600,
        columns: [
          {type: 'index',width: 50},
          {field: 'billDate', width: 100, title: '日期',filter: true,sortable: true},
          {field: 'transTypeName', width: 100, title: '业务类型',filter: true,sortable: true},
          {field: 'billNo', width: 120, title: '票号',filter: true,canClick: true},
          {field: 'billStateName', width: 100, title: '状态',filter: true},
          {field: 'salesName', width: 100, title: '业务员',filter: true,sortable: true},
          {field: 'buName', width: 220, title: '客户名称',filter: true,sortable: true,align: 'left'},
          {field: 'leftAmount', width: 100, title: '欠款',sortable: true,align: 'right', formatter: 'formatMoney',sum: true},
          {field: 'state', width: 100, title: '派单状态',filter: true,sortable: true,align: 'center'},
          {type: 'selection',width: 50,align: 'center'},
        ]
      },

    ],
    doSearch: (inject) => {
      let salesId = inject.getValue('salesId')
      let buId = inject.getValue('buId')
      let billNo = inject.getValue('billNo')
      let contactCatId = inject.getValue('contactCatId')
      let invId = inject.getValue('invId')
      let endDate = inject.getValue('endDate')
      let exceptPdBill = inject.getValue('exceptPdBill')
      let search = {
        salesId,
        buId,
        billNo: tool.xe.trim(billNo),
        contactCatId,
        invId,
        endDate,
        exceptPdBill,
      }
      tool.post('receipt/pdsk', {formData: search}, true).then(ret => {
        let list = []
        if (ret.stat && ret.data) {
          list = ret.data.list
        }
        inject.setValue('grid', list)
      })
    },
    choseBill: (inject) => {
      let list = inject.exec('grid', 'getSelect')
      if(list.length ===0) return tool.err('还没有选择票据')
      addBillToList(list)
    },
    btns: [
      {
        name: '选中', types: 'info', click: (inject) => {
          options.choseBill(inject)
        }
      },
      {
        name: '选中关关闭', types: 'info',inject: true, click: (inject, close) => {
          options.choseBill(inject)
          close()
        }
      },
    ],

  }
  tool.editor(options)

}
const changeDo = (ret) => {
  doId.value = ret ? ret.id : 0
}
const change = (data) => {
  allData.value = data
}
const del = (id) => {
  for (let i = 0; i < salesList.value.length; i++) {
    if (salesList.value[i].id === id.id) {
      salesList.value.splice(i, 1)
      sumBills()
    }
  }
}
const addBillToList = (list) => {
  let ids = []
  for (let i = 0; i < salesList.value.length; i++) {
    ids.push(tool.xe.toNumber(salesList.value[i].id))
  }
  list.map(row => {
    if (ids.indexOf(tool.xe.toNumber(row.id)) === -1) {
      salesList.value.push(row)
    }
  })
  salesList.value.map(row => {
    row.arrearsReal = tool.xe.toFixed(row.arrearsReal, 2)
    row.leftAmount = tool.xe.toFixed(row.leftAmount, 2)
  })
  sumBills()
}
const sumBills = () => {
  let ret = []
  let union = tool.xe.groupBy(salesList.value, 'id')
  salesList.value = []
  for(let it in union) {
    salesList.value.push(union[it][0])
  }
  let gp = tool.xe.groupBy(salesList.value, 'buId')
  let gpbills = tool.xe.groupBy(salesList.value, 'billNo')
  let bills =0;
  let buIds = 0;
  for(let i in gp) {
    buIds++
  }
  for(let i in gpbills) {
    bills++
  }
  allData.value.shs = buIds
  allData.value.pjs = bills
  allData.value.ys = tool.xe.toFixed(tool.xe.sum(salesList.value,'leftAmount'), 2)
  for(let buId in gp) {
    let arr = gp[buId]
    for (let i = 0; i < arr.length; i++) {
      let row = tool.xe.clone(arr[i])
      delete row._RID
      // if(i > 0) row.buName = ''
      row.arrearsReal = tool.xe.toFixed(row.arrearsReal, 2)
      row.leftAmount = tool.xe.toFixed(row.leftAmount, 2)
      ret.push(row)
    }
    // 最后一行加合计
    ret.push({
      buId: arr[0].buId,
      buName: arr[0].buName,
      transTypeName: '小计',
      arrearsReal: tool.xe.toFixed(tool.xe.sum(arr, 'arrearsReal'),2),
      leftAmount: tool.xe.toFixed(tool.xe.sum(arr, 'leftAmount'),2)
    })
  }
  hjList.value = ret
}
const confirm = () => {
  if(!doId.value) return tool.err('请选择经办人')
  let list = []
  let gpList = salesList.value
  for (let i = 0; i < gpList.length; i++) {
    if(!gpList[i].isSub && !gpList[i].isSubAll) {
      list.push({doId: doId.value,doName: doName.value, ...gpList[i]})
    }
  }
  if(list.length === 0 ) {
    return tool.err('还没有选择要收款的销售单')
  }
  tool.confirm('确认派单？','派单确认').then(() => {
    tool.post('receipt/dopd', list, true).then(ret => {
      if(ret.stat) {
        salesList.value = []
        sumBills()
        doId.value = 0
        doName.value = ''
      }
    })
  })
}


onActivated(() => { bus.$on('scan-ret', scanPs) })
onDeactivated(() => { bus.$off('scan-ret', scanPs) })

</script>
<style scoped lang="scss">
.item {
  height: 30px;
}
.tc {
  text-align: center;
}
.tr {
  text-align: right;
}
</style>